package edu.java.homework.hw03.ipj06;

/**
 * Spiral visiting of the elements of the matrix where we start from a[0][0]
 * 
 * @author Tsvetan Vasilev
 * 
 */

public class Exer06 {
    // awesome :D
    public static void main(String[] args) {
	int[][] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
		{ 13, 14, 15, 16 }

	};
	int[][] b = { { 1, 2 }, { 3, 4 } };
	int[][] c = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 },
		{ 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 },
		{ 21, 22, 23, 24, 25 } };

	int[][] d = { { 1, 2, 3, 4, 5, 6 }, { 7, 8, 9, 10, 11, 12 },
		{ 13, 14, 15, 16, 17, 18 }, { 19, 20, 21, 22, 23, 24 },
		{ 25, 26, 27, 28, 29, 30 }, { 31, 32, 33, 34, 35, 36 } };
	// printMatrix(a);
	// printMatrix(b);
	printMatrix(c);
	// printMatrix(b);
	System.out.println("\n\nSpiral visiting: ");
	spiralVisit(c);

    }

    public static void spiralVisit(int[][] matrix) {
	int length = matrix.length;
	for (int i = 0; i <= (length / 2) - 1; i++) {
	    int j = (length - 1) - i;

	    for (int k = i; k <= j; k++) {
		System.out.print(matrix[i][k] + "  ");
		// System.out.println();
	    }
	    for (int l = i + 1; l <= j - 1; l++) {
		System.out.print(matrix[l][j] + "  ");
		// System.out.println();
	    }
	    for (int m = j; m >= i; m--) {
		System.out.print(matrix[j][m] + "  ");
		// System.out.println();
	    }
	    for (int n = j - 1; n >= i + 1; n--) {
		System.out.print(matrix[n][i] + "  ");
		// System.out.println();
	    }
	}
	if ((length % 2) == 1) {
	    System.out.print(matrix[length / 2][length / 2] + "  ");
	    // System.out.println();
	}
    }

    public static void printMatrix(int[][] matrix) {
	int length = matrix.length;
	for (int i = 0; i < length; i++) {
	    for (int j = 0; j < length; j++) {
		System.out.print(matrix[i][j] + "\t");
	    }
	    System.out.println();
	}
    }

}
